package br.senai.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.senai.dao.AlunoDAO;
import br.senai.dao.MateriaDAO;
import br.senai.entity.Aluno;

@WebServlet("/AlunoServlet")
public class AlunoServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
       
    public AlunoServlet() {
       
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

			AlunoDAO ad = new AlunoDAO();
			Aluno aluno = new Aluno();

			Long matricula = Long.parseLong(request.getParameter("matricula"));
			aluno.setNome(request.getParameter("nome"));
			aluno.setCpf(request.getParameter("cpf"));
			aluno.setTelefone(request.getParameter("telefone"));
			aluno.setEmail(request.getParameter("email"));
			aluno.setEndereco(request.getParameter("endereco"));
			//programar o combobox para passar o valor do id materia
			//aluno.setIdMateria(Long.parseLong(request.getParameter("idmateria")));
			aluno.setIdMateria(Long.parseLong("1"));
			MateriaDAO md = new MateriaDAO();
			if(matricula == 0 || matricula.equals("null")){
				ad.save(aluno);
				
			} else {
				aluno.setMatricula(matricula);
				try {
					ad.edit(aluno);
				} catch (SQLException e) {
					e.getMessage();
					e.printStackTrace();
				}
			}
			try {
				Aluno a = ad.buscarAlunoCpf(aluno.getCpf());
				if(!md.verAlunoMateriaAssociado(aluno.getIdMateria(), a.getMatricula())){
					md.associarMateriaAluno(aluno.getIdMateria(), a.getMatricula());
				}
			} catch (Throwable e) {
				e.printStackTrace();
			}
			RequestDispatcher rd = request.getRequestDispatcher("ListaAluno");
			rd.forward(request, response);
	}

}
